package roadsuggester.main;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Paint;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;


//Utility class
public class Utils
{
	public static GeoPoint locationToGeoPoint(Location location)
	{
		double latitude=location.getLatitude();
		double longitude=location.getLongitude();
		GeoPoint point=new GeoPoint((int) (latitude*1e6), (int) (longitude*1e6));
		return point;
	}

	public static GeoPoint coordsToGeoPoint(double latitude, double longitude)
	{
		GeoPoint point=new GeoPoint((int) (latitude*1e6), (int) (longitude*1e6));
		return point;
	}
	
	public static Location coordsToLocation(double latitude, double longitude)
	{
		Location loc=new Location("");
		loc.setLatitude(latitude);
		loc.setLongitude(longitude);
		return loc;
	}

	public static Paint getPaint(int id, Context context)
	{
		Paint paint=new Paint();
		paint.setColor(context.getResources().getColor(id));
		paint.setStrokeWidth(3);
		paint.setStyle(Paint.Style.STROKE);
		paint.setAntiAlias(true);
		return paint;
	}

	public static GeoPoint addressToGeoPoint(Address address)
	{
		double latitude=address.getLatitude();
		double longitude=address.getLongitude();
		GeoPoint point=new GeoPoint((int) (latitude*1e6), (int) (longitude*1e6));
		return point;
	}

	public static Address findAddress(String address, Context context)
	{
		Geocoder geocoder=new Geocoder(context);
		List<Address> addresses;
		try
		{
			addresses=geocoder.getFromLocationName(address, 1);

			if(addresses.size()!=0)
			{
				return addresses.get(0);
			}
		}
		catch(IOException e)
		{
		}
		return null;
	}

	public static Map<String, Address> getFromLocationCache=new HashMap<String, Address>();	//Memoization
	public static Address getFromLocation(Context context, double lattitude, double longitude)
	{
		String hashString=lattitude+","+longitude;
		if(!getFromLocationCache.containsKey(hashString))
		{
			try
			{
				Geocoder geoCoder=new Geocoder(context);
				List<Address> addresses=geoCoder.getFromLocation(lattitude, longitude, 1);
				getFromLocationCache.put(hashString, addresses.get(0));
			}
			catch(IOException e)
			{
				getFromLocationCache.put(hashString, null);
			}
		}
		
		return getFromLocationCache.get(hashString);
	}

	public static void showToastText(Context context, String text)
	{
		showToastText(context, text, Toast.LENGTH_SHORT);
	}

	public static void showToastText(Context context, String text, int duration)
	{
		Toast toast=Toast.makeText(context, text, duration);
		toast.show();
	}

}
